import { reactive, onBeforeUnmount } from 'vue'
import { designComponent } from 'src/use/designComponent'
interface AppRoute {
    path?: string,
    hash?: string,
    param?: string
}

function getRoute(): AppRoute | null {
    let locationHash = window.location.hash
    if (!locationHash) {
        return null
    }
    if (locationHash.charAt(0) === '#') {
        locationHash = locationHash.slice(1)
    }

    if (!locationHash) {
        return null
    }
    const [path, hash] = decodeURIComponent(locationHash).split('#')
    return {
        path, hash
    }
}

export const AppNavigator = designComponent({
    name: 'app-navigator',
    props: {
        defaultPath: String
    },
    provideRefer: true,
    setup({props, event, setupContext}) {
        let initRoute = getRoute()
        if (!initRoute) {
            initRoute = { path: props.defaultPath }
        }
        const state = reactive({  // 初始化路由
            route: initRoute
        })
        const utils = {
            reset: () => { // 刷新路由
                const route = getRoute()
                if (!!route) {
                    state.route = route
                }
            }
        }
        const handler = {
            hashChange: () => utils.reset()
        }
        const methods = {
            go: (path: string) => {
                console.log('go==', path)
                window.location.hash = encodeURIComponent(path)
            }
        }
        window.addEventListener('hashchange', handler.hashChange)
        onBeforeUnmount(() => window.removeEventListener('hashchange', handler.hashChange))

        const refer = {
            state,
            methods
        };
        return {
            refer,
            render: () => {
                return !!setupContext.slots.default ? setupContext.slots.default() : null
            }
        }
    }

})
